from sqlite3 import IntegrityError

from django.http import JsonResponse
from django.db.models import Case, When, Value, CharField
from db_man_app.models import RewardPunishment, Student
import json
from datetime import datetime

def get_all(request):
    # 获取所有奖惩记录及其关联的学生信息
    rewards = RewardPunishment.objects.select_related('student').all().annotate(
        reward_type=Case(
            When(type='奖励', then=Value('奖励')),
            When(type='惩罚', then=Value('惩罚')),
            default=Value('未知'),
            output_field=CharField()
        ),
        name=Case(
            When(student__isnull=False, then='student__name'),
            default=Value(''),
            output_field=CharField()
        )
    ).order_by('-reward_date')  # 按日期降序排列
    # 构建返回数据
    tableData = []
    for reward in rewards:
        tableData.append({
            'student_id': reward.student_id,
            'name': reward.name,
            'reward_name': reward.reward_name,
            'reward_type': reward.reward_type,
            'reward_date': reward.reward_date.strftime('%Y-%m-%d'),  # 格式化日期
            'remark': reward.remark or '空'  # 处理可能的None值
        })
    return JsonResponse({
        'tableData': tableData,
        'status': 'success',
        'message': '奖惩数据获取成功'
    })


def get_students_form(request):
    try:
        data=Student.objects.all().values('student_id','name')
        return JsonResponse({
            'status': 'success',
            'data': list(data)
        },safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)

def add_one(request):
    data = json.loads(request.body)
    student_id = data['student_id']
    remark = data['remark']
    remark_type = data['reward_type']
    reward_date = data['reward_date']
    reward_name = data['reward_name']
    new_reward_date=datetime.strptime(reward_date, '%Y-%m-%dT%H:%M:%S.%fZ').date()
    try:
        RewardPunishment.objects.create(
            student_id=student_id,
            remark=remark,
            reward_date=new_reward_date,
            reward_name=reward_name,
            type=remark_type
        )
        return JsonResponse(1,safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)


def updata_one(request):
    #首先通过学号，旧的
    data = json.loads(request.body)
    student_id=data['formData']['student_id']
    reward_type=data['formData']['reward_type']
    reward_name=data['formData']['reward_name']
    new_date=data['formData']['reward_date']
    remark=data['formData']['remark']
    reward_date=datetime.strptime(new_date, '%Y-%m-%dT%H:%M:%S.%fZ').date()
    old_remark=data['remark']
    old_reward_date=data['reward_date']
    old_reward_name=data['reward_name']
    old_reward_type=data['reward_type']
    try:
        #首先按照旧的信息找到对应的条目id
        reward_id=RewardPunishment.objects.get(
            student_id=student_id,
            reward_date=old_reward_date,
            reward_name=old_reward_name,
            remark=old_remark,
            type=old_reward_type
        ).record_id
        #修改
        RewardPunishment.objects.filter(
            record_id=reward_id,
        ).update(
            reward_name=reward_name,
            remark=remark,
            reward_date=reward_date,
            type=reward_type
        )
        return JsonResponse(1,safe=False)

    except IntegrityError:
        return JsonResponse(0, safe=False)


def del_one(request):
    data = json.loads(request.body)
    student_id=data['student_id']
    reward_type=data['reward_type']
    reward_name=data['reward_name']
    reward_date=data['reward_date']
    remark=data['remark']
    try:
        RewardPunishment.objects.filter(
            student_id=student_id,
            reward_date=reward_date,
            reward_name=reward_name,
            remark=remark,
            type=reward_type
        ).delete()
        return JsonResponse(1,safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)

